<template>
  <div>
    <li
      class="todo"
      :class="{ completed: todo.done, editing: editing }"
    >
      <div class="view">
        <input
          class="toggle"
          type="checkbox"
          :checked="todo.done"
          @change="toggleTodo(todo)"
        >
        <label
          v-text="todo.text"
          @dblclick="editing = true"
        ></label>
        <button
          class="destroy"
          @click="removeTodo(todo)"
        ></button>
      </div>
      <input
        class="edit"
        v-show="editing"
        v-focus="editing"
        :value="todo.text"
        @keyup.enter="doneEdit"
        @keyup.esc="cancelEdit"
        @blur="doneEdit"
      >
    </li>
  </div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "Todo",
  props: ["todo"],
  data() {
    return {
      editing: false,
    };
  },
  methods: {
    ...mapActions(["editTodo", "toggleTodo", "removeTodo"]),
    doneEdit(e) {
      let value = e.target.value.trim();
      let { todo } = this;
      console.log(todo);
      if (!value) {
        this.removeTodo(todo);
      } else if (this.editing) {
        this.editTodo({
          todo,
          value,
        });
        this.editing = false;
      }
    },
    cancelEdit(e) {
      e.target.value = this.todo.text;
      this.editing = false;
    },
  },
  directives: {
    focus(el, { value }, { context }) {
      if (value) {
        context.$nextTick(() => {
          el.focus();
        });
      }
    },
  },
};
</script>

<style scoped>
</style>
